import type { ModelStuck } from '@/types'
import { upperFirst, toLower } from 'lodash-es'

// 入口文件代码
export const getFontendIndexCodeString = () => {
  return `
  <template>

    <div>
    <a-card title="模型名称" :bordered="false">
      <div class="data-content">

      <Data />
      </div>
    </a-card>
  </div>

</template>
<script setup lang="ts">
    import Data from "./components/data.vue";

</script>

`
}

// table的代码
export const getFontendDataCodeString = (modelStuck: ModelStuck, whiteKeyList: string[]) => {
  const newWhiteKeyList = whiteKeyList.concat(['onlyId', 'editor', 'creator', 'orgId'])
  const filterFields = modelStuck?.content.filter((item) => !newWhiteKeyList.includes(item.name))

  const tableItems = filterFields.map((item) => {
    return `
    <a-table-column
    title="${item.remark}"
    :width="200"
  >
    <template #cell="{ record }">
      <span>{{record.${item.name}}}</span>
    </template>
  </a-table-column>`
  })

  const queryItems = filterFields.map((item) => {
    return `
    <a-form-item
            field="${item.name}"
            label="${item.remark}"
          >
            <a-input${item.type === 'string' ? '' : '-number'}
              v-model="queryParams.${item.name}"
              placeholder="请填写${item.remark}"
              allow-clear
            />
          </a-form-item>
    `
  })

  const tableDataString = `
  <template>
    <div>

    <div class="data-content" ref="dataContentRef">

      <!-- 查询 -->
      <div>
        <a-form :model="queryParams" layout="inline">

        ${queryItems.join('\n\n')}

          <a-form-item>
            <a-button type="primary" @click="queryRequest">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
          </a-form-item>
        </a-form>

        <div class="my-20px flex justify-between">
          <a-space>
            <a-button type="primary" @click="newHandle">
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
          </a-space>
        </div>
      </div>
      <!-- 数据表格 -->
      <a-table
        :data="tableData"
        page-position="bottom"
        table-layout-fixed
        row-key="onlyId"
        :pagination="{
          total: dataTotalSize,
          current: pageInex,
          showTotal: true,
        }"
        :scrollbar="false"
        :loading="requestLoading"
        :scroll="{
          x: '100%',
          y: tableHeightCupt,
        }"
        @page-change="onPageChangeHandle"
      >
        <template #columns>
          ${tableItems.join('\n\n')}
          <a-table-column
            title="操作"
            fixed="right"
            align="center"
            :width="240"
          >
            <template #cell="{ record }">
              <a-space>
                <a-popconfirm
                  content="确认要删除这条数据?"
                  position="tr"
                  @ok="onDeleteConfirm(record)"
                >
                  <a-button type="text" status="danger">
                    <template #icon> <icon-delete /> </template>删除</a-button
                  >
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <DataForm ref="dataFormRef" @success="onSuccess" />
  </div>
  </template>

  `

  const reqKeyList = filterFields.map((item) => {
    return (item.type == 'string' ? `${item.name}?: ""` : `${item.name}?: -1`) + `//${item.remark},`
  })

  const scriptString = `
<script setup lang="ts">
import DataForm from "./dataForm.vue";

import { reactive, ref, computed } from "vue";
import { get${upperFirst(modelStuck.modelName)}List, delete${upperFirst(modelStuck.modelName)} } from "@/api";
import type {
  Get${upperFirst(modelStuck.modelName)}ListReq,
  ${upperFirst(modelStuck.modelName)}Item,
} from "@/api";
import { Message } from "@arco-design/web-vue";
import { useElementSize } from "@vueuse/core";

interface DataEle extends HTMLElement {
  showCreateFromTopModal: () => void;
}
const dataFormRef = ref<DataEle>();

const dataContentRef = ref();

const { height: tableHeight } = useElementSize(dataContentRef);
const tableHeightCupt = computed(() => tableHeight.value - 200);

const tableData = ref<${upperFirst(modelStuck.modelName)}Item[]>([]);
const dataTotalSize = ref(0);
const pageInex = ref(1);

const requestLoading = ref(false);

const queryParams = reactive({
  ${reqKeyList.join('\n  ')}
});

const getDataListRequest = async () => {
  const params:  Get${upperFirst(modelStuck.modelName)}ListReq = {
    pageIndex: pageInex.value, // 当前页码
    pageSize: 10, // 每页显示条数
    ...queryParams,
  };
  requestLoading.value = true;
  const res = await get${upperFirst(modelStuck.modelName)}List(params);
  requestLoading.value = false;
  tableData.value = res.data.list || [];
  dataTotalSize.value = res.data.total;
};

const onPageChangeHandle = (page: number) => {
  pageInex.value = page;
  getDataListRequest();
};

const onDeleteConfirm = async (record:  ${upperFirst(modelStuck.modelName)}Item) => {
  const deleteRes = await delWhiteList({
    onlyId: record.onlyId,
  });
  if (deleteRes.code == 200) {
    Message.success("删除成功～");
    if (tableData.value.length == 1 && pageInex.value > 1) {
      pageInex.value = pageInex.value - 1;
    }
    getDataListRequest();
  }
};

const queryRequest = () => {
  pageInex.value = 1;

  getDataListRequest();
};

const onSuccess = () => {
  getDataListRequest();
};

const newHandle = () => {
  dataFormRef.value?.showCreateFromTopModal();
};

getDataListRequest();
</script>
  `

  return tableDataString + scriptString
}

export const getFontendDataFormString = (modelStuck: ModelStuck, whiteKeyList: string[]) => {
  const newWhiteKeyList = whiteKeyList.concat(['onlyId', 'editor', 'creator', 'orgId'])
  const filterFields = modelStuck?.content.filter((item) => !newWhiteKeyList.includes(item.name))

  const formItems = filterFields.map((item) => {
    return `
    <a-form-item
            field="${item.name}"
            label="${item.remark}"
            :rules="[{ required: true, message: '请填写${item.remark}' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input${item.type == 'string' ? '' : '-number'}
              style="width: 330px"
              v-model="dataForm.${item.name}"
              placeholder="请填写${item.remark}"
            />
          </a-form-item>
    `
  })

  const reqParamsString = filterFields.map((item) => {
    return `
    ${item.name}: ${item.type == 'string' ? '' : 0}, // ${item.remark}
    `
  })

  return `
  <template>
  <div>
    <a-modal
      v-model:visible="visible"
      :on-before-ok="handleOk"
      @cancel="onCancel"
      width="60%"
      :mask-closable="false"
    >
      <template #title> {{ modalTitle }} </template>
      <div>
        <a-form :model="dataForm" @submit="handleOk" ref="menuFormRef">
          ${formItems.join('')}
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">

import { ref, reactive } from "vue";

import { create${upperFirst(modelStuck.modelName)}, update${upperFirst(modelStuck.modelName)} } from "@/api";

import type {
  Create${upperFirst(modelStuck.modelName)}Req,
  ${upperFirst(modelStuck.modelName)}Item,
  Update${upperFirst(modelStuck.modelName)}Req,
} from "@/api";
import { Message } from "@arco-design/web-vue";

const visible = ref(false);
const modalTitle = ref("");

const menuFormRef = ref();
const updateId = ref("");

const emit = defineEmits(["success"]);

const initialState = (): Create${upperFirst(modelStuck.modelName)}Req => ({
 ${reqParamsString.join('')}
});

let dataForm = reactive<Create${upperFirst(modelStuck.modelName)}Req>(initialState());
const showCreateFromTopModal = () => {
  visible.value = true;
  modalTitle.value = "新建";
};

const showUpdateFromRecord = (record: ${upperFirst(modelStuck.modelName)}Item) => {
  visible.value = true;
  modalTitle.value = "编辑";
  dataForm = Object.assign(dataForm, record);
  updateId.value = record.onlyId as string;
};

const handleOk = async () => {
  const errors = await menuFormRef.value.validate();
  if (errors) {
    return false;
  }
  if (updateId.value) {
    const updateReq: Update${upperFirst(modelStuck.modelName)}Req = {
      ...dataForm,
      onlyId: updateId.value,
    };
    const updateRes = await update${upperFirst(modelStuck.modelName)}(updateReq);
    if (updateRes.code == 200) {
      if (updateRes.code == 200) {
        Message.success("修改成功～");
        emit("success");
      }
      return;
    }
  }
  const req: Create${upperFirst(modelStuck.modelName)}Req = {
    ...dataForm,
  };
  const creatRes = await create${upperFirst(modelStuck.modelName)}(req);
  if (creatRes.code == 200) {
    Message.success("创建成功～");
    emit("success");
  }
  clearForm();
};

const onCancel = () => {
  visible.value = false;
  clearForm();
};
const clearForm = () => {
  updateId.value = "";
  Object.assign(dataForm, initialState());
};

defineExpose({
  showCreateFromTopModal,
  showUpdateFromRecord,
});
</script>

  `
}
